/**
 * 
 */
package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * @author Fleischhacker
 *
 */
public class ClientTCPThread extends Thread {
	
	private Socket sock;
	private Client parent;
	private boolean alive;
	
	public ClientTCPThread(Socket _sock, Client _parent){
		this.sock = _sock;
		this.parent = _parent;
		alive = false;
	}

	public void run(){
		BufferedReader in = null;
		String line = null;
		try{
			alive = true;
			while(alive){
				in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
				while((line = in.readLine()) != null){
					if(!line.startsWith("#")) //'#' used as client-command related sign
						System.out.println(line);
					else if(line.startsWith("#resock")){
						alive = false;
						break;
					}
					else if(line.startsWith("#stop")){ //Shutdown from Server
						alive = false;
						System.out.println("= Connection closed! ");
						//System.out.println("= Press ENTER to terminate Client");
						System.out.println("= TERMINATE CLIENT!");
						break;
					}
					if(line.startsWith("Successfully logged in as")){//Saving the Client's name
						parent.setClientUser(line.split(" ")[4]);
					}
				}
			}
		}catch(IOException ioe){//When the Socket gets closed or shutdown is executed
			//System.out.println("IOException @ run!");
			System.out.println("= Socket on Server closed!");
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			alive = false;
			try {
				if(in != null)
					in.close();
				if(sock != null)
					sock.close();
			} catch (IOException e) {e.printStackTrace();}
			finally{
				if(line != null && line.startsWith("#resock")){
					parent.resock();
				}
				else
					parent.shutdown();
			}
		}
	}
	
	/**
	 * Shutdown-Command
	 */
	public void shutdown(){
		try{
			alive = false; //Breaks the while
			if(sock != null)
				sock.close();
		}catch(IOException ioe){
			System.out.println("ERROR @ClientTCPThread.shutdown():"+ioe.getMessage());
		}
	}
}
